<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <h1 style="text-align: center;">文档新增页面</h1>
            </div>
            <el-form ref="documentRef" :model="form" :rules="rules" label-position="top" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="所属档案" prop="archiveId">
                            <el-input v-model="form.archiveId" placeholder="请输入所属档案" @blur="getArchiveById" />
                        </el-form-item>
                        <el-form-item label="文件名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入文件名称" />
                        </el-form-item>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="文件类型" prop="fileType">
                                    <el-select v-model="form.fileType" placeholder="请选择文件类型">
                                        <el-option v-for="dict in iams_media_type" :key="dict.value" :label="dict.label"
                                            :value="dict.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="文件大小(Kb)" prop="fileSize">
                                    <el-input type="number" v-model="form.fileSize" placeholder="请输入文件大小(Kb)" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="文件路径" prop="filePath">
                            <el-input v-model="form.filePath" placeholder="请输入文件路径" />
                        </el-form-item>
                        <el-form-item label="挂载目录" prop="directory">
                            <el-tree-select v-model="form.directory" :data="directory" check-strictly
                                :render-after-expand="false" style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="存放位置" prop="fileLocation">
                            <el-input v-model="form.fileLocation" placeholder="请输入存放位置" />
                        </el-form-item>
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="真实性" prop="authenticity" label-position="left">
                                    <el-switch v-model="form.authenticity" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="完整性" prop="integrity">
                                    <el-switch v-model="form.integrity" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="可用性" prop="availability">
                                    <el-switch v-model="form.availability" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="安全性" prop="security">
                                    <el-switch v-model="form.security" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="上传文件">
                            <el-upload ref="upload" class="upload-demo" :action="uploadFileUrl" :headers="headers"
                                :limit="1" :on-change="handleChange" :on-exceed="handleExceed" :on-success="handleSuccess" :auto-upload="false">
                                <template #trigger> <el-button type="primary">选择文件</el-button> </template>
                                <el-button class="ml-3" type="success" @click="submitUpload"> 上传至服务器 </el-button>
                                <template #tip>
                                    <div class="el-upload__tip text-red"> 一次只能上传一个文件，重复上传会覆盖之前上传的文件 </div>
                                </template>
                            </el-upload>
                        </el-form-item>

                        <el-form-item label="文件内容">
                            <editor v-model="form.content" :min-height="200" />
                        </el-form-item>

                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入备注内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </template>
        </el-card>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, reactive } from 'vue'
import { genFileId, ElTreeSelect } from 'element-plus'
import { addDocument, getMaxXuhao } from "@/api/manage/document";
import { getArchive, addDirectoryFiles } from "@/api/manage/archive";     //updateDirectoryFiles => addDirectoryFiles已修改，后端也要做相应的修改
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();
const { iams_media_type } = proxy.useDict('iams_media_type');

const data = reactive({
    form: {
        id: null,
        archiveId: null,
        xuhao: null,
        name: null,
        fileType: null,
        fileSize: 0,
        filePath: null,
        fileLocation: null,
        content: null,
        authenticity: null,
        integrity: null,
        availability: null,
        security: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        directory: null
    },
    rules: {
        name: [
            { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
    }
});

const archive = ref({});
const directory = ref([]);
const { form, rules } = toRefs(data);

// 取消按钮
function cancel() {
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        archiveId: null,
        xuhao: null,
        name: null,
        fileType: null,
        fileSize: 0,
        filePath: null,
        fileLocation: null,
        content: null,
        authenticity: null,
        integrity: null,
        availability: null,
        security: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        directory: null
    };
    proxy.resetForm("documentRef");
}

/* 上传地址 */
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传excel文件地址
/* 上传请求头 */
const headers = ref({ Authorization: "Bearer " + getToken() });

/** 提交按钮 */
function submitForm() {
    proxy.$refs["documentRef"].validate(valid => {
        if (valid) {
            // 将布尔值转换为整型
            const formData = {
                ...form.value,
                authenticity: form.value.authenticity ? 1 : 0,
                integrity: form.value.integrity ? 1 : 0,
                availability: form.value.availability ? 1 : 0,
                security: form.value.security ? 1 : 0,
            };
            console.log('Current form:', formData); // 添加日志输出



            addDocument(formData).then(response => {
                proxy.$modal.msgSuccess("新增成功");

                /** 将document的id赋值给formData.id，从而在archive的directory中更新 */
                formData.id = response;
                // console.log('formData.id:', formData.id);
                addDirectoryFiles(formData).then(response => {                 //已修改
                    console.log('Directory updated successfully:', response.code);
                }).catch(error => {
                    console.error('Error updating directory:', error);
                });

                proxy.$router.push({ path: "/manage/document/doc-list" });
            });
        }
    });
}
/** 搜索档案 */
function getArchiveById() {
    // console.log('getArchiveById triggered')
    if (!form.value.archiveId) {
        proxy.$modal.msgError("请输入档案ID");
        return;
    }
    getMaxXuhao(form.value.archiveId).then(response => {
        form.value.xuhao = response.data + 1;
    });

    getArchive(form.value.archiveId).then(response => {
        // console.log('API Response:', response.data); // 添加日志输出
        if (response.code == 200 && response.data) {
            proxy.$modal.msgSuccess("档案存在");
            // 确保 response.data.directory 是一个数组
            let directoryData = [];
            if (typeof response.data.directory === 'string') {
                try {
                    directoryData = JSON.parse(response.data.directory);
                } catch (e) {
                    console.error('Failed to parse JSON:', e);
                    proxy.$modal.msgError("解析目录数据失败");
                    return;
                }
            } else if (Array.isArray(response.data.directory)) {
                directoryData = response.data.directory;
            }

            // console.log('directoryData:', directoryData); // 添加日志输出

            directory.value = directoryData.map(item => ({
                value: item.id,
                label: item.label,
                children: item.children ? item.children.map(child => ({
                    value: child.id,
                    label: child.label
                })) : []
            }));

            // console.log('directory.value:', directory.value); // 添加日志输出

            archive.value = response.data;
        } else {
            proxy.$modal.msgError("档案不存在");
        }
    }).catch(error => {
        console.error('API Error:', error); // 添加日志输出
        proxy.$modal.msgError("查询档案失败：" + error.message);
    });
}

const upload = ref()
const handleChange = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles);
    let filename = uploadFile.raw.name;
    let filesize = uploadFile.raw.size;
    let filetype = filename.substring(filename.lastIndexOf(".") + 1);
    let lastmodifieddate = uploadFile.raw.lastModifiedDate;
    // 确保 form 不为 undefined
    if (data.form) {
        data.form.name = filename;
        data.form.fileType = filetype;
        data.form.fileSize = Number((filesize / 1024).toFixed(1));
        // data.form.filePath = uploadFile.raw.name;
        // console.log('Updated form:', data.form); // 添加日志输出
    } else {
        console.error('form is undefined');
    }
    // console.log('Calling form:', form.value); // 添加日志输出
}

const handleExceed = (files) => {
    upload.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    upload.value.handleStart(file)
}

const handleSuccess = (response) => {
    if (response.code === 200) {
        proxy.$modal.msgSuccess("上传成功");
        data.form.filePath = response.url;
        console.log('Updated response:', response);
    } else {
        proxy.$modal.msgError(response.msg);
    }

}

const submitUpload = () => {
    upload.value.submit()
}
</script>